<template>
    <van-loading v-if="isLoading" type="spinner" />
   <van-icon
      v-else
      :color="zan === 1 ? '#3296fa':'#777'"
      :name="zan === 1 ? 'good-job':'good-job-o'"
      @click="zanHandler"
    />
</template>
<script>
import {
  addArticleZan,
  deleteArticleZan
} from '@/api/article'
import { mapGetters } from 'vuex'
  export default {
    name: 'ZanArticle',
    props: {
      // 文章是否被点赞
      zan:{
        type:Number,
        required:true
      },
      // 文章id
      articleId:{
        type:[String,Number],
        required:true
      }
    },
    data () {
      return {
          isLoading:false // 是否加载中  
      }
    },
    computed: {
      ...mapGetters(['token'])
    },
    methods: {
      // 点赞、取消点赞事件
      async zanHandler(){
        if(!this.token) return this.$toast.fail('请登录后操作')
        this.isLoading = true
        try {
          if(this.zan === 1){
            // 点赞了，要取消
            await deleteArticleZan(this.articleId)
          }else{
            // 未点赞，要点赞
            await addArticleZan({
              target:this.articleId
            })
          }
          this.$toast.success('操作成功')
          const newZan = this.zan === 1 ? 0 : 1
          this.$emit('update:zan',newZan)
        } catch (error) {
          console.log(error);
           this.$toast.fail('操作失败')
        }
        this.isLoading = false
      }
    },
    created () {},
    mounted () {},
  }
</script>
<style   scoped>
</style>